//
//  MTRedpackTool.swift
//  MT
//
//  Created by ooops on 2019/12/22.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
/// 网络请求

import RxSwift
import RxDataSources
import Moya
import Result


public class MTRedpackTool: NSObject {
    
    static let `default`: MTRedpackTool = MTRedpackTool()
    
    let disposedBag: DisposeBag = DisposeBag()
    
    let provider: MTProvider = MTProvider<MTRedPackApi>()
    
    public override init() {
        super.init()
    }
}

// MARK: - 发送红包界面
extension MTRedpackTool {
    
    /// 聚会任务群主发红包专用接口
    /// - Parameters:
    ///   - presentViewController: presentViewController description
    ///   - conversation: conversation description
    ///   - partyTaskId: 聚会任务id
    ///   - callBack: callBack description
    func sendRedpack(_ presentViewController: UIViewController, _ conversation: JMSGConversation, _ partyTaskId: Int, callBack: @escaping RedpacketCallBack) {
        let sendRedpackVC: MTSendRedpackViewController = MTSendRedpackViewController(conversation, partyTaskId: partyTaskId) { (flag) in
            callBack(flag)
        }
        
        let nav: BaseNavController = BaseNavController(rootViewController: sendRedpackVC)
        
        nav.modalPresentationStyle = .fullScreen
        
        presentViewController.present(nav, animated: true, completion: nil)
    }
    
    /// 弹出发送红包控制器
    /// - Parameters:
    ///   - presentViewController: 哪里弹
    ///   - conversation: 会话消息对象
    ///   - callBack: 回调
    func sendRedpack(_ presentViewController: UIViewController, _ conversation: JMSGConversation, callBack: @escaping RedpacketCallBack) {
        let sendRedpackVC: MTSendRedpackViewController = MTSendRedpackViewController(conversation) { flag in
            callBack(flag)
        }
        
        let nav: BaseNavController = BaseNavController(rootViewController: sendRedpackVC)
        
        nav.modalPresentationStyle = .fullScreen
        
        presentViewController.present(nav, animated: true, completion: nil)
    }
}


// MARK: - 红包发送相关
extension MTRedpackTool {
    /// 发送红包
        /// - Parameters:
        ///   - requestParam: 红包参数
        ///   - callBack: 发送红包回调
        func sendRedpack(_ requestParam: [String : Any], _ callBack: @escaping (_ model: MTRedpackModel?, _ success: Bool) -> Swift.Void) {
            
            let r = requestParam["partyTaskId"] != nil
            
            provider.rx.requestResult(r ? .partySendRedpack(requestParam) : .sendRedpack(requestParam)).subscribe(onNext: { (result:Result<MTRedpackModel, AnyError> , isCache:Bool) in
                switch result {
                case .success(let listModel):
                    callBack(listModel, true)
                case .failure(_):
                    callBack(nil, false)
                    break
                }
                
            }).disposed(by: disposedBag)
            
        }
}

// MARK: - 红包查询相关
extension MTRedpackTool {
    
    /// 查询红包收入 / 支出信息
    /// - Parameter presentViewController: vc
    func queryRedpack(queryParam: [String : Any], _ presentViewController: UIViewController, _ callBack: @escaping (_ model: MTQueryRedpackModel?, _ success: Bool) -> Swift.Void) {
        provider.rx.requestResult(.queryRedpackList(queryParam)).subscribe(onNext: { (result:Result<MTQueryRedpackModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let listModel):
                callBack(listModel, true)
            case .failure(_):
                callBack(nil, false)
                break
            }

        }).disposed(by: disposedBag)
    }
    
    /// 获取红包状态信息后的处理
    /// - Parameters:
    ///   - redpacketId: 红包id
    ///   - callBack: 回调
    ///   - from: 1 - 个人红包, 2 - 俱乐部 / 广场红包
    func redpackInfo(_ presentViewController: UIViewController, redpacketId: Int, from: Int, msgId: String, type: MTRedpacketType, callback: (() -> Void)?) {
        MTRedpackTool.default.getRedpack(redpacketId: redpacketId) { (redpackModel, isSuccess) in
            /// 查询红包状态
            //if isSuccess, let code = redpackModel?.code, code == 200 {
            redpackModel?.sendType = from
            if isSuccess, let status = redpackModel?.result?.status {
                let info = MTRedpacketInfo.create(msgId: msgId, status: status, type: type)
                MTRedpacketInfoDB.shareInstance.insertData(info)
                /// 如果是已经打开过的红包 / 已经领取完毕
                switch status {
                case .owner:
                    self.redpackDetail(presentViewController, redpackModel: redpackModel!)
                case .opened:
                    self.redpackDetail(presentViewController, redpackModel: redpackModel!)
                    info.status = MTOpenRedpackStatus.opened
                    MTRedpacketInfoDB.shareInstance.updateRedpacketMessage(info)
//                    if type != .platform {
                        callback?()
//                    }
                case .clearance:
                    /// 个人红包被领完 - 进详情
//                    if let type = redpackModel?.sendType, type == 1 {
                    self.redpackDetail(presentViewController, redpackModel: redpackModel!)
                    info.status = MTOpenRedpackStatus.clearance
                    MTRedpacketInfoDB.shareInstance.updateRedpacketMessage(info)
//                    if type != .platform {
                        callback?()
//                    }
//                    } else {
//                        self.openRedpack(presentViewController, redpackModel: redpackModel!)
//                    }
                case .invalid:
                    self.openRedpack(presentViewController, redpackModel: redpackModel!, msgId: msgId, type: type, callback: callback)
                    info.status = MTOpenRedpackStatus.invalid
                    MTRedpacketInfoDB.shareInstance.updateRedpacketMessage(info)
                    //if type != .platform {
                        callback?()
//                    }
                case .failed:
                    self.openRedpack(presentViewController, redpackModel: redpackModel!, msgId: msgId, type: type, callback: callback)
                    break
                default:
                    self.openRedpack(presentViewController, redpackModel: redpackModel!, msgId: msgId, type: type, callback: callback)
                }
            }
        }
    }
    
    
    /// 红包领取详情
    /// - Parameters:
    ///   - presentViewController: presentViewController description
    ///   - redpackModel: redpackModel description
    private func redpackDetail(_ presentViewController: UIViewController, redpackModel: MTOpenRedpackModel) {
        presentViewController.navigationController?.pushViewController(MTOpenRedpackDetailViewController(redpackModel), animated: true)
    }
    
    
    /// 弹出领红包界面
    /// - Parameters:
    ///   - presentViewController: presentViewController description
    ///   - redpackModel: redpackModel description
    private func openRedpack(_ presentViewController: UIViewController, redpackModel: MTOpenRedpackModel, msgId: String, type: MTRedpacketType, callback: (() -> Void)?) {
        let nav = BaseNavController(rootViewController: MTOpenRedpackViewController(redpackModel, msgId: msgId, type: type, callback: callback))
        let presentTransition: MTModalTransition = MTModalTransition()
        nav.transitioningDelegate = presentTransition
        nav.modalPresentationStyle = .custom
        nav.modalTransitionStyle = .crossDissolve
        DispatchQueue.main.async {
            presentViewController.present(nav, animated: true, completion: nil)
        }
    }
    
}


// MARK: - 红包领取相关
extension MTRedpackTool {
    
    /// 获取红包状态信息
    /// - Parameters:
    ///   - redpacketId: 红包id
    ///   - callBack: 回调
    private func getRedpack(redpacketId: Int, _ callBack: @escaping (_ model: MTOpenRedpackModel?, _ success: Bool) -> Swift.Void) {
        let requestParam = ["sendId" : redpacketId]
        provider.rx.requestResult(.getRedpack(requestParam)).subscribe(onNext: { (result:Result<MTOpenRedpackModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let listModel):
                callBack(listModel, true)
            case .failure(_):
                callBack(nil, false)
                break
            }
            
        }).disposed(by: disposedBag)
    }
    
    
    /// 领取红包
    /// - Parameters:
    ///   - redpacketId: 红包id
    ///   - callBack: 回调
    func openRedpack(redpacketId: Int, _ callBack: @escaping (_ model: MTOpenRedpackModel?, _ success: Bool) -> Swift.Void) {
        let requestParam = ["sendId" : redpacketId]
        provider.rx.requestResult(.openRedpack(requestParam)).subscribe(onNext: { (result:Result<MTOpenRedpackModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let listModel):
                callBack(listModel, true)
            case .failure(_):
                callBack(nil, false)
                break
            }

        }).disposed(by: disposedBag)
    }
    
}
